/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.service;

import java.util.List;
import server.constants.ClientConstants;
import server.constants.GlobalConstants;
import server.dao.ClientDAO;
import server.domain.Client;

/**
 *
 * @author fillipe
 */
public class ClientService {

    private ClientDAO clientDAO;

    public ClientService() {
        this.clientDAO = new ClientDAO();
    }

    public String insert(Client client) {
        try {
            if (clientDAO.getByCPF(client.getCpf()) != null) {
                return ClientConstants.NOT_SAVED_CPF_EXISTS;
            }
            clientDAO.save(client);
            return String.format("%s \n %s", ClientConstants.SAVED, client.toString());
        } catch (Exception e) {
            return GlobalConstants.ERROR_SAVE;
        }
    }

    public String update(Client client) {
        try {
            if (!getById(client.getId()).getCpf().equals(client.getCpf())) {
                if (clientDAO.existClientOrder(client.getId())) {
                    return ClientConstants.NOT_UPDATED_HAVE_ORDERS;
                }
            }
            Client c = clientDAO.getByCPF(client.getCpf());
            if (c != null && c.getId() != client.getId()) {
                return ClientConstants.NOT_UPDATED_CPF_EXISTS;
            }
            clientDAO.update(client);
            return String.format("%s \n %s", ClientConstants.UPDATED, client.toString());
        } catch (Exception e) {
            return GlobalConstants.ERROR_UPDATE;
        }
    }

    public String delete(Client client) {
        try {
            if (getById(client.getId()) == null) {
                return ClientConstants.CLIENT_NOT_FOUND;
            }
            if (clientDAO.existClientOrder(client.getId())) {
                return ClientConstants.NOT_DELETED_HAVE_ORDERS;
            }
            clientDAO.delete(client);
            return String.format("%s", ClientConstants.DELETED);
        } catch (Exception e) {
            return GlobalConstants.ERROR_DELETE;
        }
    }

    public Client getById(Long id) {
        try {
            return clientDAO.getById(id);
        } catch (Exception ex) {
            return null;
        }
    }

    public List<Client> getByName(String name) {
        try {
            return clientDAO.getByName(name);
        } catch (Exception ex) {
            return null;
        }
    }

    public Client getByCPF(String cpf) {
        try {
            return clientDAO.getByCPF(cpf);

        } catch (Exception ex) {
            return null;
        }
    }
}
